package com.zk.util;


/**
 * java 实现队列
 * @author zzx
 *
 */
public class Queue {
	
	private int [] queArray;
    private int maxSize;
    public int front;   //存储队头元素的下标
    public int rear;    //存储队尾元素的下标
    public static int length; //队列元素个数
    //构造方法，初始化队列
    public Queue(int maxSize){
           this.maxSize = maxSize;
           queArray = new int[maxSize];
           front = 0;
           rear = -1;
           length = 0;
    }
    //插入一个元素
    public void insert(int elem) throws Exception{
           if(isFull()){
                  throw new Exception("队列已满，不能进行插入操作！");
           }
           //如果队尾指针已到达数组的末端，插入到数组的第一个位置
           if(rear == maxSize-1){
                 rear = -1;
           }
           queArray[++rear] = elem;
           length++;
    }
    
  //删除
    public int remove() throws Exception{
           if(isEmpty()){
                  throw new Exception("队列为空，不能进行移除操作！");
           }
           //如果队头指针已到达数组末端，则移到数组第一个位置
           if(front == maxSize){
                  front = 0;
           }
           int item = queArray[front++];
           length--;
           return item;
    }
    
    //查看队头元素
    public int peek() throws Exception{
           if(isEmpty()){
                  throw new Exception("队列内没有元素！");
           }
           return queArray[front];
    }
    //获取队列长度
    public int size(){
           return length;
    }
    //判空
    public boolean isEmpty(){
           return (length == 0);
    }     
    //判满
    public boolean isFull(){
           return (length == maxSize);
    } 
    
    public void printArr() {
    	for(int i=0;i<length;i++) {
    		System.err.print(queArray[i]+",");
    	}
    	System.err.println("********************原数组**********************");
    	for(int i=0;i<queArray.length;i++) {
    		System.err.print(queArray[i]+",");
    	}
    }
	public static void main(String[] args) throws Exception {
		
	  Queue que = new Queue(10);
  	  que.insert(1);
  	  que.insert(2);
  	  que.insert(3);
  	  que.insert(4);
  	  que.insert(5);
  	  que.insert(6);
  	  System.out.println(que.peek());
  	  System.out.println(length);
  	  System.out.println(que.remove());
  	  System.out.println(que.peek());
  	  System.err.println("所有数组");
  	  que.printArr();
	}

}
